import os
import sys
from typing import Callable

import serial.tools.list_ports
from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QDialog, QApplication, QHBoxLayout, QPushButton


from ClientUi.controls import CustomList
from ClientUi.controls.CustomList import CustomListItemType
from ClientUi.deviceManager.deviceManagerBaseDlg import deviceManagerBaseDlg


class searchSerialPortDlg(deviceManagerBaseDlg):
    __id = 0
    __saveSignal = pyqtSignal(int, str)

    def __init__(self, id_: int):
        super().__init__()
        self.__id = id_
        self.setFixedSize(400, 250)
        self.setWindowIcon(QIcon(f'{self._clientUiPath}\\images\\icon.ico'))  # 设置窗口图标
        self.setWindowTitle('串口搜索')
        # plcList = self._getDevList()
        self.SetMidLayoutMargins(0, 20, 0, 2)
        self.SetSaveBtnName('确定')

    def _onInitTopWidget(self):
        pass

    def _onInitDevListHeader(self, devList: CustomList):
        devList.SetColumnTitleAndTypes((('序号', CustomListItemType.LABEL), ('串口名称', CustomListItemType.LABEL)))

    def _onAddWidgetsInBottomLeft(self, layout: QHBoxLayout):
        searchBtn = QPushButton('搜索')
        searchBtn.clicked.connect(self.__clickSearch)
        layout.addWidget(searchBtn, 0, Qt.AlignLeft)

    def _onSave(self):
        infos = self.__getCurrentRowInfo()
        if infos is not None:
            name = infos[1]
            self.__saveSignal.emit(self.__id, name)
        self.accept()

    def __getCurrentRowInfo(self):
        rowIndex = self._getDevList().currentRow()
        if rowIndex >= 0:
            return self._getDevList().getRow(rowIndex)
        return None

    def __clickSearch(self):
        print(f'__clickSearch')
        # serial.Serial('COM1', 9600, timeout=0.5)
        try:
            s = serial.tools.list_ports.comports()
            self._getDevList().setRowCount(len(s))
            for i, port in enumerate(s):
                self._getDevList().setRow(i, (f'{i + 1}', port.name))
            if len(s) > 0:
                self._getDevList().selectRow(0)
        except Exception as e:
            print('枚举串口异常')
            print("Unexpected error:", sys.exc_info())

    def connect(self, cb: Callable[[int, str], None]):
        self.__saveSignal.connect(cb)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    try:
        current_path = os.path.abspath(__file__)
        path = os.path.dirname(current_path)
        path = os.path.dirname(path)
        app.setStyleSheet(open(f'{path}/styleSheet.qss', encoding='utf-8').read())
        window = searchSerialPortDlg(1)
        window.showNormal()
        sys.exit(app.exec_())

    except Exception as e:
        print(e)


